import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { Button, Spin, Row, Col, Input, Radio, Checkbox, Modal, DatePicker, Tabs , message} from 'antd';
import mapKeys from 'lodash/mapKeys';
import mapValues from 'lodash/mapValues';
const TabPane = Tabs.TabPane;
import { WeaSwitch } from 'comsMobx';
import {WeaDialog, WeaNewScroll, WeaSelect, WeaBrowser, WeaDatePicker, WeaTimePicker, WeaTextarea,WeaAlertPage,
  WeaInput, WeaUpload, WeaSearchGroup, WeaFormItem, WeaTableEdit, WeaTools, WeaLocaleProvider, WeaInputNumber
} from 'ecCom';
const getKey = WeaTools.getKey;
const getLabel = WeaLocaleProvider.getLabel;

import * as apis from '../../apis/dialog.js';
import MySwitch from './mySwitch';
import Screen from './screen.js';

@inject('meetingDialog', 'meetingCalView')
@observer
class Create extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      params: {
        crmIDs: [],
        docIDs: [],
        projectIDs: [],
        taskIDs: [],
        requestIDs: [],
        attachs: [],
        beginDate: '',
        endDate: '',
        remindType: '',
        none: '',
      },
      type: 'create',
      topicChange: false, //是否出发了会议议程的onchange事件
      serviceChange: false, //是否出发了会议服务的onchange事件
    }
  }

  componentWillMount () {
    let {type} = this.props
    if (type == 'edit' && type != this.state.type) {
      this.setState({type: 'editfirst'})
    }
  }

  componentDidMount() {
    const { getMeetingTabElement } = this.props.meetingDialog;
    getMeetingTabElement();
  }

  componentWillReceiveProps (nextProps) {

    if (this.state.type != nextProps.type) {
      this.setState({type: nextProps.type})
    }
  }

  shouldComponentUpdate (nextProps, nextState) {
    const { dialogStatus:{type,createInit} } = this.props.meetingDialog;
    if(type == 'create'){
      if(createInit){
        return true;
      }else{
        return false;
      }
    }
    return true
  }

  componentWillUnmount () {
    //组件卸载时一般清理一些状态
    let {meetingDialog} = this.props;
    meetingDialog.deleteForms();
  }

  getCondition = () => {
    let {meetingId} = this.props
    let {dialogStatus} = this.props.meetingDialog
    let {conditions} = toJS(dialogStatus)
    let key = meetingId == '' ? 'create' : meetingId
    if (conditions[key]) {
      return conditions[key]
    } else {
      return false
    }
  }

  browserDemand = (oldFields, oldValue) => {
    let {meetingDialog:{dialogStatus, ecCallerVisible}} = this.props;
    let {hasCaller,type,meetingId} = dialogStatus;
    let newFields = {...oldFields}
    let newValue = {...oldValue}
    let {isInterval} = this.props
    if (newFields.domkey[0] == 'meetingtype') {//会议类型-新建周期会议，在搜索时要多传个参数
      newFields.browserConditionParam.dataParams = {isInterval: '0'}
      if (isInterval) newFields.browserConditionParam.dataParams = {isInterval: '1'}
    }else if (ecCallerVisible && newFields.domkey[0] == 'caller') {//会议类型-召集人直接的联动，在搜索时要多传个参数
      newFields.browserConditionParam.dataParams = {meetingtype: newValue['meetingtype'] ? newValue['meetingtype'] : ''}
      newFields.browserConditionParam.completeParams = {meetingtype: newValue['meetingtype'] ? newValue['meetingtype'] : ''}
      
      if (hasCaller) {
        newFields.browserConditionParam.type="meetingCaller";
        newFields.browserConditionParam.tabs=[];
      }else{
        newFields.browserConditionParam.type="1";
      }
    }else if(newFields.domkey[0] == 'address'){
      newFields.browserConditionParam.dataParams = {beginDate: newValue['begindate'],beginTime:newValue['begintime'],endDate: newValue['enddate'],endTime:newValue['endtime'],meetingid:type=='change'?meetingId:''}
      newFields.browserConditionParam.completeParams = {beginDate: newValue['begindate'],beginTime:newValue['begintime'],endDate: newValue['enddate'],endTime:newValue['endtime'],meetingid:type=='change'?meetingId:''}
    }else {
      newFields.browserConditionParam.dataParams = {...newFields.browserConditionParam.dataParams,secretLevel: newValue['secretLevel'] ? newValue['secretLevel'] : ''}
      newFields.browserConditionParam.completeParams = {...newFields.browserConditionParam.completeParams,secretLevel: newValue['secretLevel'] ? newValue['secretLevel'] : ''}
    }
    return newFields
  }

  isRequired = (oldFields, oldValue) => {
    let clone = {...oldFields}
    let arr = []
    if (oldValue.address != '' || (oldValue.customizeAddress != '' && oldValue.customizeAddress != undefined)) {
      clone = {...clone, viewAttr: 2}
      delete clone.rules
      arr.push(clone)
      arr.push(false)
      return arr
    } else if (oldValue.address == '' && (oldValue.customizeAddress == '' || oldValue.customizeAddress == undefined)) {
      clone = {...clone, viewAttr: 3, rules: 'required'}
      arr.push(clone)
      arr.push(true)
      return arr
    }
  }

  isHrmRequired = (oldFields, oldValue) => {
    let clone = {...oldFields}
    let arr = []
    if (oldValue.hrmmembers != '' || (oldValue.hrmDepartments != '' && oldValue.hrmDepartments != undefined) || (oldValue.hrmSubCompanys != '' && oldValue.hrmSubCompanys != undefined)) {
      clone = {...clone, viewAttr: 2}
      delete clone.rules
      arr.push(clone)
      arr.push(false)
      return arr
    } else if (oldValue.hrmmembers == '' && (oldValue.hrmDepartments == '' || oldValue.hrmDepartments == undefined) && (oldValue.hrmSubCompanys == '' || oldValue.hrmSubCompanys == undefined)) {
      clone = {...clone, viewAttr: 3, rules: 'required'}
      arr.push(clone)
      arr.push(true)
      return arr
    }
  }

  setFormCondition = (name, value, props, data) => {
    const {meetingDialog, meetingId} = this.props;
    let {conditions} = toJS(meetingDialog.dialogStatus);
    const key = meetingId == '' ? 'create' : meetingId;
    const conditioninfo = this.getCondition();

    if(data){
      conditioninfo && conditioninfo.length > 0 && conditioninfo.map((v,index) => {
        v.items && v.items.length > 0 && v.items.map((m, n) => {
          getKey(m) === name && (conditioninfo[index].items[n][props][data] = value);
        })
      })
    }else {
      conditioninfo && conditioninfo.length > 0 && conditioninfo.map((v,index) => {
        v.items && v.items.length > 0 && v.items.map((m, n) => {
          getKey(m) === name && (conditioninfo[index].items[n][props] = value);
        })
      })
    }
    this.props.meetingDialog.setConditions(key, conditioninfo)
  }

  inputNumberChange = (key, args) => {
    let obj = {
      value: args[0] || '',
    };
    if (args[1]) obj.valueSpan = args[1];
    if (args[2]) obj.valueObj = args[2];
    let res = {}; res[key] = obj;
    this.props.onChange && this.props.onChange(res, obj);
  }

  getSearchs = () => {
    let {meetingId, meetingCalView, meetingDialog, isSingle} = this.props;
    let {form, getFormParams, uploadParams, getFormBrowserType,canRender} = meetingDialog;
    uploadParams = toJS(uploadParams);

    let {type} = this.state;
    let conditioninfo = this.getCondition();
    if (!conditioninfo) conditioninfo = [];
    let key = meetingId == '' ? 'create' : meetingId;
    let isFormInit = false;
    if (form[key]) {
      isFormInit = form[key].isFormInit
    }

    const singleStyle = { //会议室使用情况 单页样式
      position: 'absolute',
      top: 6,
      right: -104,
    };

    const dialogStyle = { //会议室使用情况 弹框样式
      paddingLeft: 15
    };

    let value = getFormParams(key)
    let group = [];

    type != 'editfirst' && isFormInit && canRender && conditioninfo.length!==0 && conditioninfo.map((c,index) => {
      let items = []
      c && c.items && c.items.map(fields => {
        let richtextKey = "";
        if(fields.conditionType == 'RICHTEXT' && value.hasOwnProperty(fields.domkey[0])){
          richtextKey = fields.domkey[0];
        }
        if(fields.domkey[0] == 'meetingtype'){//会议类型 + 新增会议类型
         fields.browserConditionParam.addOnClick = () =>{
           if(window.weaMeetingEngine){
             const setState = window.weaMeetingEngine && window.weaMeetingEngine.store.meetingTypeSetStore && window.weaMeetingEngine.store.meetingTypeSetStore.setState;
             setState({showTypeDialog: true, createOrEdit: 0});
           }
         }
        }
        if(fields.domkey[0] == 'address'){//会议地点 + 新增会议室
          fields.browserConditionParam.addOnClick = () => {
            if(window.weaMeetingEngine){
              const setState = window.weaMeetingEngine && window.weaMeetingEngine.store.meetingRoomSetStore && window.weaMeetingEngine.store.meetingRoomSetStore.setState;
              setState({showCreate: true, createOrEdit: 0});
            }
          }
        }

        if (fields.conditionType == 'BROWSER') {
          fields = this.browserDemand(fields, value)
        }
        //在前端单独处理附件为图片的原因：前端已经将category以及uploadurl当做公共的全局使用了，不管后端还是前端修改都会改所有的附件的url，所以单独修改
        let uploadUrl = '';
        if(fields.conditionType == 'UPLOAD' ){
          uploadUrl = uploadParams[fields.domkey[0]].uploadUrl
          if(fields.listType == 'img' && uploadUrl.indexOf('listType=img') < 0){
            uploadUrl = uploadUrl+"&listType=img"
          }
        }

        let variable = true
        if (fields.domkey[0] == 'address' || fields.domkey[0] == 'customizeAddress') {
          let Temporary = this.isRequired(fields, value)
          fields = Temporary[0]
          variable = Temporary[1]
        }
        // if (fields.domkey[0] == 'hrmmembers' || fields.domkey[0] == 'hrmDepartments' || fields.domkey[0] == 'hrmSubCompanys') {
        //   let Temporary = this.isHrmRequired(fields, value)
        //   fields = Temporary[0]
        //   variable = Temporary[1]
        // }

        //处理重复模式repeatType，选择联动的校验问题（将联动隐藏项的非必填改为必填） -- satrt
        //1--按天重复
        if(fields.domkey[0] == 'repeatdays' && value['repeatType'] == 1){
          fields.viewAttr = 3
          fields.rules='required'
        }
        //2--按周重复
        if(fields.domkey[0] == 'repeatweeks' && value['repeatType'] == 2){
          fields.viewAttr = 3
          fields.rules='required'
        }
        if(fields.domkey[0] == 'rptWeekDays' && value['repeatType'] == 2){
          fields.viewAttr = 3
          fields.rules='required'
          fields.browserConditionParam.viewAttr = 3
          fields.browserConditionParam.rules='required'
        }
        //3--按月重复
        if(fields.domkey[0] == 'repeatmonths' && value['repeatType'] == 3){
          fields.viewAttr = 3
          fields.rules='required'
        }
        if(fields.domkey[0] == 'repeatmonthdays' && value['repeatType'] == 3){
          fields.viewAttr = 3
          fields.rules='required'
        }
        //处理重复模式repeatType，选择联动的校验问题（将联动隐藏项的必填改为非必填） -- end
       
        if((!value['remindTypeNew'] || getFormBrowserType('remindTypeNew',key) == 'INPUT') &&
          (fields.domkey[0] == 'remindImmediately' ||
            fields.domkey[0] == 'remindBeforeStart' ||
            fields.domkey[0] == 'remindBeforeEnd')) {
          return
        }else {
          if(fields.domkey[0] == 'remindBeforeStart' || fields.domkey[0] == 'remindBeforeEnd'){//提醒开始时间 提醒结束时间 上传组件单独处理
            items.push({
              com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@wh6n1f@${fields.domkey[0]}`}
                label={`${fields.label}`}
                labelCol={{span: `${fields.labelcol}`, offset: '2'}}
                wrapperCol={{span: 11}}>
                <MySwitch ecId={`${this && this.props && this.props.ecId || ''}_MySwitch@ci825e@${fields.domkey[0]}`} meetingType='create' canset={false} fieldConfig={fields} form={form[key]} onChange={this.onChange}/>
              </WeaFormItem>),
              colSpan: 1
            })
          }else {
            items.push({
              com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@z8qdso@${fields.domkey[0]}`}
                label={`${fields.label}`}
                labelCol={{span: `${fields.labelcol}`, offset: '2'}}
                wrapperCol={{span: 11}}
                className={fields.domkey[0] != 'address' ? '' : 'address'}
                error={variable ? form[key].getError(fields) : form[key].getError(fields)}
                tipPosition='bottom'
              >
                {fields.conditionType == 'UPLOAD' ?
                  <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@ujwana@${fields.domkey[0]}`}
                    {...uploadParams[fields.domkey]}
                    uploadUrl={uploadUrl}
                    onChange={(ids, list) => {
                      form[key].updateFields({
                        [fields.domkey]: ids
                      })
                      meetingDialog.setUploadParams({
                        [fields.domkey]: {
                          datas: list
                        }
                      })
                    }}
                  />
                   :
                   (fields.conditionType == 'RICHTEXT' && fields.viewAttr == 1 ?
                   <div class="wea-field-readonly  " dangerouslySetInnerHTML = {{ __html: value[richtextKey]}}></div>
                    :
                    <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@itkbqt@${fields.domkey[0]}`} fieldConfig={fields} form={form[key]} onChange={this.onChange}/>)
                }
                {fields.domkey[0] != 'address' ? '' :
                  <span style={{position: 'absolute', right: '-128px',bottom: '5px',maxWidth: '114px'}}>
                    <a 
                     onClick={() => {
                       meetingCalView.isMeetingUsageBtn = false;
                       this.props.setRoomPlan(true)}
                     }
                  >{getLabel(15881,"会议室使用情况")}</a></span>}
              </WeaFormItem>),
              colSpan: 1,
              hide: form[key].isHide(fields, (keys, allParams) => {
                let bool = false;
                //重复模式repeatType相关联动
                fields.domkey[0] === 'repeatdays' && value['repeatType'] != 1 && (bool = true);
                fields.domkey[0] === 'repeatweeks' && value['repeatType'] !=2 && (bool = true);
                fields.domkey[0] === 'rptWeekDays' && value['repeatType'] !=2  && (bool = true);
                fields.domkey[0] === 'repeatmonths' && value['repeatType'] !=3 && (bool = true);
                fields.domkey[0] === 'repeatmonthdays' && value['repeatType'] !=3 && (bool = true);
                return bool;
              })
            })
          }
        }
      })
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@7l9iiq@${index}`} col={1} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
    })
    return group
  }

  uploadChange = (ids, list) => {
    let { meetingDialog , meetingId} = this.props;
    let { form } = meetingDialog;
    let key = meetingId == '' ? 'create' : meetingId;
    form[key].updateFields({
      [fields.domkey]: ids
    })
    meetingDialog.setUploadParams({
      [fields.domkey]: {
        datas: list
      }
    })
  }

  onChange = (paramsObj) => {
    let {meetingId, meetingDialog} = this.props;

    let key = meetingId == '' ? 'create' : meetingId;
    let {form, getFormParams,setOldSecretLevel,oldSecretLevel,baseDocFlowColumn, dialogStatus, setDialogState,serviceDocFlowColumn, topicDocFlowColumn, ecCallerVisible, setAccessoryBaseInfo,isLimitCreateMeetingBeginEndTime} = meetingDialog;
    let {topicDatas, serviceDatas, editDatas} = toJS(dialogStatus);
    let datas_topicField = this.state.topicChange ? topicDatas : editDatas&&editDatas.topic&&editDatas.topic.datas?editDatas.topic.datas:[]; //处理onChange事件再次重制datas
    let datas_serviceField = this.state.serviceChange ? serviceDatas : editDatas&&editDatas.service&&editDatas.service.datas?editDatas.service.datas:[]; //处理onChange事件再次重制datas
    let value = getFormParams(key)

    // 开始---结束时间限制
    if(isLimitCreateMeetingBeginEndTime) {
      if(paramsObj['begindate'] && (paramsObj['begindate'].value >= value.enddate)){
        if(paramsObj['begindate'].value == value.enddate &&  value.begintime >  value.endtime) {
          form[key].updateFields({endtime: value.begintime});
        }else{
          form[key].updateFields({enddate: paramsObj['begindate'].value});
        }
      }
      if(paramsObj['enddate'] && paramsObj['enddate'].value!='' && (paramsObj['enddate'].value <= value.begindate)){
        if(paramsObj['enddate'].value == value.begindate &&  value.begintime >  value.endtime) {
          form[key].updateFields({begintime: value.endtime});
        }else{
          form[key].updateFields({begindate: paramsObj['enddate'].value})
        }
      }
      if(paramsObj['begintime'] && (value.begindate >= value.enddate) && (paramsObj['begintime'].value > value.endtime)){
        form[key].updateFields({endtime: paramsObj['begintime'].value})
      }
      if(paramsObj['endtime'] &&paramsObj['endtime'].value!='' &&  (value.begindate >= value.enddate) && (paramsObj['endtime'].value < value.begintime)){
        form[key].updateFields({begintime: paramsObj['endtime'].value})
      }
    }

    if (paramsObj.secretLevel) {//判断密级
      //密级等级是否小于当前使用等级
      const secretLevel = paramsObj['secretLevel'].value
      if(parseInt(secretLevel,10) > parseInt(oldSecretLevel,10)){
        let _that = this
        //清空文档和流程
        Modal.confirm({
          title: `${getLabel(131329,'信息确认')}`,
          content: `${getLabel(500701,'【密级】级别已更改且小于上次选择，文档、流程资源会被清空')}`,
          onOk() {
            //更新会议信息中的字段
            baseDocFlowColumn&&baseDocFlowColumn.forEach((element,index)=>{
              form[key].updateFields({
                [element]: {
                  value: '',
                  valueSpan: '',
                  valueObj: ''
                }
              })
            })
            //更新议程中文档/流程/日程/会议浏览按钮字段
            if(topicDocFlowColumn&&topicDocFlowColumn.length > 0){
              let newTopicData = [];
              newTopicData = datas_topicField.map((x) => {
                topicDocFlowColumn.forEach((val,index)=>{
                  x = {...x,[val]:'',[val+'span']:''}
                })
                return x
              })
              if(_that.state.topicChange){
                setDialogState({topicDatas:newTopicData})
              }else{
                setDialogState({editDatas:{...editDatas,topic:{...editDatas.topic,datas:newTopicData}}});
              }
              _that.tableEditChange('topic',newTopicData)

            }
            
            //更新服务中文档/流程/日程/会议浏览按钮字段
            if(serviceDocFlowColumn&&serviceDocFlowColumn.length > 0){
              let newServiceData = [];
              newServiceData = datas_serviceField.map((x) => {
                serviceDocFlowColumn.forEach((val,index)=>{
                  x = {...x,[val]:'',[val+'span']:''}
                })
                return x
              })
              _that.state.serviceChange ? setDialogState({serviceDatas:newServiceData}) : setDialogState({editDatas:{...editDatas,service:{...editDatas.service,datas:newServiceData}}});
              _that.tableEditChange('service',newServiceData)
            }

            setOldSecretLevel(paramsObj['secretLevel'].value)
          },
          onCancel() {
            form[key].updateFields({
              secretLevel: {
                value: oldSecretLevel
              }
            })
          },
        });
      }else{
        setOldSecretLevel(paramsObj['secretLevel'].value)
      }
      
    }

    if (paramsObj.hrmmembers) {//选择参会人员,自动计算人数
      form[key].updateFields({
        totalmember: {
          value: paramsObj.hrmmembers.valueObj.length
        }
      })
    }
    if (paramsObj.crmmembers) {//选择参会客户,自动计算客户人数
      form[key].updateFields({
        crmtotalmember: {
          value: paramsObj.crmmembers.valueObj.length
        }
      })
    }

    if (paramsObj.remindHoursBeforeEnd) {
      form[key].updateFields({
        remindHoursBeforeEnd: {
          value: paramsObj['remindHoursBeforeEnd'].value
        }
      })
    }

    if (paramsObj.remindHoursBeforeStart) {
      form[key].updateFields({
        remindHoursBeforeStart: {
          value: paramsObj['remindHoursBeforeStart'].value
        }
      })
    }

    if (paramsObj.remindTimesBeforeEnd) {//选择参会客户,自动计算客户人数
      form[key].updateFields({
        remindTimesBeforeEnd: {
          value: paramsObj['remindTimesBeforeEnd'].value
        }
      })
    }

    if (paramsObj.remindTimesBeforeStart) {
      form[key].updateFields({
        remindTimesBeforeStart: {
          value: paramsObj['remindTimesBeforeStart'].value
        }
      })
    }
    

    if (paramsObj.meetingtype) {  //选择会议类型一系列联动
      let params = ecCallerVisible ? {
        caller: value.caller,
        hrmmembers: value.hrmmembers,
        crmmembers: value.crmmembers,
        meetingtype: paramsObj.meetingtype.value,
      } : {
        hrmmembers: value.hrmmembers,
        crmmembers: value.crmmembers,
        meetingtype: paramsObj.meetingtype.value,
      }

      const uploadParams = toJS(meetingDialog.uploadParams);
      const uploadKeys = toJS(meetingDialog.uploadKeys);
      let canChange = true;
      uploadKeys.map(key => {//上传附件字段是否已经有值的判断，有就不需要改了
        if(uploadParams[key].datas.length !== 0){
          canChange = false
        }
      })
      apis.changeBroserMeetingType(params).then((result) => {
        let callerValue = '', callerValueSpan = '', hrmmembersValue = '', hrmmembersValueSpan = '',
          crmmembersValue = '', crmmembersValueSpan = '';
          ecCallerVisible && setDialogState({
            hasCaller: result.hasCaller,
          })
        if (ecCallerVisible && result.caller.length > 0) {//召集人
          let arrValue = [], arrValueSpan = []
          result.caller.forEach((element, index) => {
            arrValue.push(element.id)
            arrValueSpan.push(element.name)
          })
          callerValue = arrValue.join(',');
          callerValueSpan = arrValueSpan.join(',');
        }
        if (result.hrmmembers.length > 0) {//参会人
          let arrValue = [], arrValueSpan = []
          result.hrmmembers.forEach((element, index) => {
            arrValue.push(element.id)
            arrValueSpan.push(element.name)
          })
          hrmmembersValue = arrValue.join(',');
          hrmmembersValueSpan = arrValueSpan.join(',');
        }
        if (result.crmmembers.length > 0) {//参会客户
          let arrValue = [], arrValueSpan = []
          result.crmmembers.forEach((element, index) => {
            arrValue.push(element.id)
            arrValueSpan.push(element.name)
          })
          crmmembersValue = arrValue.join(',');
          crmmembersValueSpan = arrValueSpan.join(',');

        }
        if(result.uploadcfg && Object.keys(result.uploadcfg).length > 0 && canChange){//相关附件(3个条件)
          meetingDialog.setUploadCommonParams({
            category: result.uploadcfg.category || '',
            maxUploadSize: Number(result.uploadcfg.maxUploadSize) || 0,
            mixUploadSize: Number(result.uploadcfg.mixUploadSize) || 0,
            uploadUrl: result.uploadcfg.uploadUrl,
            errorMsg: result.uploadcfg.errorMsg || '',
          })
          setAccessoryBaseInfo({
            category: result.uploadcfg.category || '',
            maxUploadSize: Number(result.uploadcfg.maxUploadSize) || 0,
            mixUploadSize: Number(result.uploadcfg.mixUploadSize) || 0,
            uploadUrl: result.uploadcfg.uploadUrl,
            errorMsg: result.uploadcfg.errorMsg || '',
          })
        }
        if ( ecCallerVisible ) {
          form[key].updateFields({
            caller: {
              value: result.caller.length > 0 ? callerValue : '',
              valueSpan: result.caller.length > 0 ? callerValueSpan : '',
              valueObj: result.caller
            },
            hrmmembers: {
              value: result.hrmmembers.length > 0 ? hrmmembersValue : '',
              valueSpan: result.hrmmembers.length > 0 ? hrmmembersValueSpan : '',
              valueObj: result.hrmmembers
            },
            totalmember: {
              value: result.hrmmembers.length
            },
            crmmembers: {
              value: result.crmmembers.length > 0 ? crmmembersValue : '',
              valueSpan: result.crmmembers.length > 0 ? crmmembersValueSpan : '',
              valueObj: result.crmmembers
            },
            crmtotalmember: {
              value: result.crmmembers.length
            },
          })
        } else {
          form[key].updateFields({
            hrmmembers: {
              value: result.hrmmembers.length > 0 ? hrmmembersValue : '',
              valueSpan: result.hrmmembers.length > 0 ? hrmmembersValueSpan : '',
              valueObj: result.hrmmembers
            },
            totalmember: {
              value: result.hrmmembers.length
            },
            crmmembers: {
              value: result.crmmembers.length > 0 ? crmmembersValue : '',
              valueSpan: result.crmmembers.length > 0 ? crmmembersValueSpan : '',
              valueObj: result.crmmembers
            },
            crmtotalmember: {
              value: result.crmmembers.length
            },
          })
        }
      })
    }
    if (paramsObj.address && paramsObj.address.value) {//输入会议室内容 清空自定义会议室内容
      value.customizeAddress != '' && form[key].updateFields({
        customizeAddress: {
          value: ''
        }
      })
    }
    if (paramsObj.customizeAddress && paramsObj.customizeAddress.value) {//输入自定义会议室内容 清空会议室内容
      value.address != '' && form[key].updateFields({
        address: {
          value: '',
          valueSpan: '',
          valueObj: [],
        }
      })
    }
  }

  getTab = () => {
    let {type, meetingId, isSingle} = this.props;
    let {dialogStatus, getNewServiceDatas,saveFields,oldSecretLevel,weaDialogContentHeight,accessoryBaseInfo, meetingCreateTabs,setEditTableCloumnCount} = this.props.meetingDialog;
    let {topicColumns, topicDatas, serviceColumns, serviceDatas, editDatas, conditions} = toJS(dialogStatus);
    let columns_topicField = topicColumns || [];
    let datas_topicField = topicDatas || [];
    let datas_topicField_temp = datas_topicField
    let columns_serviceField = serviceColumns || [];
    let datas_serviceField = serviceDatas || [];
    let datas_serviceField_temp = datas_serviceField;
    let uploadCfg = {};

    let key = meetingId == '' ? 'create' : meetingId;
    conditions[key] && conditions[key].forEach(record => {
      record && record.items && record.items.forEach(_record => {
        if (_record.domkey[0] == 'accessorys') {
          uploadCfg = _record.cfg
        }
      })
    })

    if ((type == 'edit' && editDatas && (editDatas.topic || editDatas.service)) || (type == 'create') ) {

      let newTop = type == 'edit'? editDatas.topic&&editDatas.topic.columns && editDatas.topic.columns.length > 0 && editDatas.topic.columns.filter((e) => {
        if (e['render']) {
          delete e['render']
        }
        return !!e['com']
      }):type=='create'?topicColumns&&topicColumns.filter((e) => {
        if (e['render']) {
          delete e['render']
        }
        return !!e['com']
      }):''
      let newSer = type == 'edit'? editDatas.service&&editDatas.service.columns && editDatas.service.columns.length > 0 && editDatas.service.columns.filter((e) => {
        if (e['render']) {

          delete e['render']
        }
        return !!e['com']
      }):type=='create'?serviceColumns&&serviceColumns.filter((e) => {
        if (e['render']) {
          delete e['render']
        }
        return !!e['com']
      }):''
      if(newSer){
        let countService = 100 / newSer.length
        columns_serviceField = newSer.map((x,index) => {
          let viewattr = x.com && x.com[0] && x.com[0].viewAttr;
          x['width'] = `${countService}%`
          if (x.com[0].type == 'BROWSER') {
            x.com[0].browserConditionParam.layout = document.body
            x.com[0].browserConditionParam.dataParams = {...x.com[0].browserConditionParam.dataParams,secretLevel: oldSecretLevel}
            x.com[0].browserConditionParam.completeParams = {...x.com[0].browserConditionParam.completeParams,secretLevel: oldSecretLevel}
          }
          if (x.com[0].type == 'FILEDUPLOAD') {
            let otherParams = x.com[0].otherParams&&x.com[0].otherParams || {}
            let listType = otherParams&&otherParams.listType || ''
            let uploadUrl = accessoryBaseInfo.uploadUrl
            if(listType == 'img' && uploadUrl.indexOf('listType=img') < 0){
              uploadUrl = uploadUrl+"&listType=img"
            }
            
            return {
              title:x.title,
              key:x.key,
              dataIndex:x.dataIndex,
              com:[{
                type: 'custom',
                key: x.key,
                viewAttr: viewattr,
                render: (text, record, index, onEdit) => {
                  return <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@b36gag@${x.key}_${index}`}
                    btnSize='small'
                    {...accessoryBaseInfo}
                    {...otherParams}
                    uploadUrl = {uploadUrl}
                    viewAttr={viewattr}
                    autoUpload={true}//自动上传
                    isDetail={true}
                    showClearAll={false}
                    // errorMsg={''}
                    datas={record[x.dataIndex]&& record[x.dataIndex].datas}
                    onChange={(ids, list) => {
                      onEdit({
                        record: {
                          ...record,
                          [x.key]: {
                            datas: list
                          },
                        }, 
                        index, 
                      })
                    }}
                  >
                  </WeaUpload>
              }
              }
              ]
            }
          }
          return x
        })
      }
      datas_serviceField = this.state.serviceChange ? serviceDatas : type=='create'?datas_serviceField_temp:editDatas.service.datas; //处理onChange事件再次重制datas

      if(newTop){
        let countTop = 100 / newTop.length;
        columns_topicField = newTop.map((x, index) => {
          let viewattr = x.com && x.com[0] && x.com[0].viewAttr;
          x['width'] = `${countTop}%`
          if (x.com[0].type == 'BROWSER') {
            x.com[0].browserConditionParam.layout = document.body
            x.com[0].browserConditionParam.dataParams = {...x.com[0].browserConditionParam.dataParams,secretLevel: oldSecretLevel}
            x.com[0].browserConditionParam.completeParams = {...x.com[0].browserConditionParam.completeParams,secretLevel: oldSecretLevel}
          }
          if (x.com[0].type == 'FILEDUPLOAD') {
            let otherParams = x.com[0].otherParams&&{...x.com[0].otherParams} || {}
            let listType = otherParams&&otherParams.listType || ''
            let uploadUrl = accessoryBaseInfo.uploadUrl
            if(listType == 'img' && uploadUrl.indexOf('listType=img') < 0){
              uploadUrl = uploadUrl+"&listType=img"
            }
            return {
              title:x.title,
              key:x.key,
              dataIndex:x.dataIndex,
              com:[{
                type: 'custom',
                key: x.key,
                viewAttr: viewattr,
                render: (text, record, index, onEdit) => {
                  return <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@92boue@${x.key}_${index}`}
                    btnSize='small'
                    {...accessoryBaseInfo}
                    {...otherParams}
                    uploadUrl = {uploadUrl}
                    viewAttr={viewattr}
                    autoUpload={true}//自动上传
                    isDetail={true}
                    showClearAll={false}
                    // errorMsg={''}
                    datas={record[x.dataIndex] && record[x.dataIndex].datas}
                    onChange={(ids, list) => {
                      onEdit({
                        record: {
                          ...record,
                          [x.key]: {
                            datas: list
                          },
                            
                        }, 
                        index, 
                      })
                    }}
                  >
                  </WeaUpload>
                }
              }
              ]
            }
          }
          return x
        })
      }
      datas_topicField = this.state.topicChange ? topicDatas : type=='create'?datas_topicField_temp:editDatas.topic.datas; //处理onChange事件再次重制datas
    }
    let styleHeight = isSingle ? '100%' : this.props.contentHeight - 46;
    if (isSingle && this.refs.singleTab) {
      styleHeight = this.refs.singleTab.clientHeight - 52;
    }
    let pane = [
      <TabPane ecId={`${this && this.props && this.props.ecId || ''}_TabPane@gqri67@meetingBase`} tab={getLabel(24249,"会议信息")} key="1">
        <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@oa67q3@meetingBase`} height={styleHeight}>
          <div>
            {this.getSearchs()}
          </div>
        </WeaNewScroll >
      </TabPane>
    ]
    const scrollParams = (cloumn, height) => {
      return {
        x: cloumn.length > setEditTableCloumnCount ? 100*cloumn.length : '', 
        y: height-45-40
      };
    };
    if (meetingCreateTabs && meetingCreateTabs.some(v => v === 'topic')) {
      pane.push(
        <TabPane ecId={`${this && this.props && this.props.ecId || ''}_TabPane@rvqs82@meetingTopic`} tab={getLabel(383590,"会议议程")} key="2">
          <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@uljc36@meetingTopic`} height={styleHeight}>
            <WeaTableEdit ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEdit@4w888u@meetingTopic`}
              ref='topicEdit'
              title={getLabel(383558,"议程列表")}
              datas={datas_topicField}
              columns={columns_topicField}
              onChange={this.topicDataChange}
              viewAttr={2}
            tableProps={{scroll: scrollParams(columns_topicField, styleHeight)}}
              draggable={true}
            />
          </WeaNewScroll >
        </TabPane>
      )
    }
  
    if (meetingCreateTabs && meetingCreateTabs.some(v => v === 'service')) {
      pane.push(
        <TabPane ecId={`${this && this.props && this.props.ecId || ''}_TabPane@hjorgm@meetingService`} tab={getLabel(383591,"会议服务")} key="3">
          <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@29hikl@meetingService`} height={styleHeight}>
            <WeaTableEdit ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEdit@i0tjzg@meetingService`}
              ref='serviceEdit'
              title={getLabel(383557,"服务列表")}
              datas={datas_serviceField}
              columns={columns_serviceField}
              onChange={this.serviceDataChange}
              viewAttr={2}
              style={{minHeight: '200px'}}
              tableProps={{
                scroll: scrollParams(columns_serviceField, styleHeight)
              }}
              draggable={true}
            />
          </WeaNewScroll >
        </TabPane>,
      )
    }
    if (meetingCreateTabs && meetingCreateTabs.some(v => v === 'sign')) {
      pane.push(
        <TabPane ecId={`${this && this.props && this.props.ecId || ''}_TabPane@uaqm7x@meetingSign`} tab={getLabel(383592,"会议签到")} key="4">
          <div className="weadialog-tabsign-screen" style={{height : styleHeight}}>
            <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@8cwoqa@meetingSign`} height={'100%'}>
              {/*<Screen ref="meetingScreen" meetingId={meetingId} onChange={this.returnState} isCreate={true}/>*/}
              <Screen ecId={`${this && this.props && this.props.ecId || ''}_Screen@iatjnr@meetingSign`} ref="meetingScreen" type={this.props.type} meetingid={meetingId}/>
            </WeaNewScroll>
          </div>
        </TabPane>
      )
    }

    if (type == 'change') {
      return pane[0]
    }
    let newPane = pane.map((e) => { return e })
    return newPane
  }

  topicDataChange = (datas)=>{
    this.setState({topicChange: true}); 
    this.tableEditChange('topic', datas)
  }

  serviceDataChange = (datas)=>{
    let {getNewServiceDatas} = this.props.meetingDialog;
    getNewServiceDatas(datas).then(result => {
      this.setState({serviceChange: true});
      this.tableEditChange('service', result)
    })
  }

  returnState = (state) => {
    let {dialogStatus, saveFields} = this.props.meetingDialog;
    let {allCreateDatas} = toJS(dialogStatus);
    allCreateDatas = {...allCreateDatas, screenParams: state};
    saveFields(allCreateDatas);
  }

  tableEditChange (type, datas) {
    let {dialogStatus, getMeetingTopicField, getMeetingServiceField, saveFields} = this.props.meetingDialog;
    let {allCreateDatas} = toJS(dialogStatus);
    let servicerows = '';
    let topicrows = '';
    let each = {};
    let alldatas = {};
    //该项为隐藏项，需要默认指定，后端需要使用
    //为什么没有服务：因为服务采用的直接删除添加的方式
    let editColumns = ['topic_data'];
    datas.forEach((element, index) => {
      each = mapKeys(element, (value, key) => {
        index == 0 &&editColumns.push(key);
        return key + '_' + (index + 1)
      })
      alldatas = {...alldatas, ...each}
    })
    alldatas = mapValues(alldatas, (value, key) => {
      let t_value = value;
      if (value && value.datas) { // 附件特殊处理 附件保存附件id
        if(value.datas instanceof Array) {
          let arr = [];
          value.datas.map(res => {
            arr.push(res.fileid);
          })
          t_value = arr;
        }
      }
      return t_value;
    })
    // 移除所有topic/service数据脏数据，如果还有数据的话会影响添加删除功能
    for (let key in allCreateDatas) {
      editColumns.forEach((c)=>{
        if(key.indexOf(c+"_")>-1){
          delete allCreateDatas[key]
        }
      })
      
    }
    if (type == 'topic') {
      topicrows = datas.length;
      alldatas = {
        ...alldatas,
        topicrows: topicrows || 0,
      }
      getMeetingTopicField(datas)
    }
    if (type == 'service') {
      servicerows = datas.length;
      alldatas = {
        ...alldatas,
        servicerows: servicerows || 0,
      }
      getMeetingServiceField(datas)
    }
    allCreateDatas = {...allCreateDatas, ...alldatas}
    saveFields(allCreateDatas)
  }

  tabChangeCheck = (e) => {//改变tab页的时候，当前页面的校验,校验成功才可以切换
    const {previewmeetingTab} = toJS(this.props.meetingDialog.dialogStatus);
    if(previewmeetingTab == 1 && e != 1){//会议信息 校验
      this.props.handleSubmit(this.props.type, this.props.meetingId, () => this.onChangeTab(e));
      this.props.meetingDialog.dialogStatus.submitLoading=false;
      this.props.meetingDialog.dialogStatus.saveLoading=false;
    }else if(previewmeetingTab == 2 && e!= 2){//会议议程 校验
      if(this.refs.topicEdit && this.refs.topicEdit.refs.edit.doRequiredCheck().pass){
        this.onChangeTab(e)
      }else{
        message.error(`${getLabel(384010, '存在必填项未填写')}`);
      }
    }else if(previewmeetingTab == 3 && e != 3){//会议服务 校验
      if(this.refs.serviceEdit && this.refs.serviceEdit.refs.edit.doRequiredCheck().pass){
        this.onChangeTab(e);
      }else{
        message.error(`${getLabel(384010, '存在必填项未填写')}`);
      }
    }else {
      this.onChangeTab(e);
    }
  }

  onChangeTab = (e) => {
    let {changePreviewMeetingTab} = this.props.meetingDialog;
    changePreviewMeetingTab(e);
  }

  render () {
    const {meetingDialog,type,isInterval} = this.props;
    let {previewmeetingTab,onlyFlowCreate,hideCreateEntry,workflowBaseIds} = toJS(meetingDialog.dialogStatus);
    let baseIdsArr = [];
    if(workflowBaseIds != ''){
      baseIdsArr = workflowBaseIds.split(',')
    }
    return (
      <div style={{height: '100%'}} ref='singleTab' className="meeting-create-dialog-container">
        {((((onlyFlowCreate==0&&hideCreateEntry==0) || isInterval)&&type == 'create') || type == 'edit' || type == 'change')&&<Tabs ecId={`${this && this.props && this.props.ecId || ''}_Tabs@q0g4yi`} activeKey={`${previewmeetingTab}`} onChange={this.tabChangeCheck}>
          {
            this.getTab()
          }
        </Tabs>}
        {onlyFlowCreate==1 && hideCreateEntry==1&& type=='create' && !isInterval&&<div style={{height:'100%'}}>
          <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@b4i8x9`} icon="icon-blog-blank">
              {getLabel(510049, '请通过流程新建会议！')}
          </WeaAlertPage>
        </div>}
        {onlyFlowCreate==1 && hideCreateEntry==0&&baseIdsArr.length == 0 && type=='create'&&!isInterval&&<div style={{height:'100%'}}>
        <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@u3kfb2`} icon="icon-blog-blank">
              {getLabel(510148, '系统查找不到新建会议流程！')}
          </WeaAlertPage>
        </div>}
      </div>
    )
  }
}

export default Create
